package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import cn.tedu.storage.service.StorageService;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class StorageTccActionImpl implements StorageTccAction {
    @Autowired
    private StorageMapper storageMapper;


    @Transactional
    @Override
    public boolean prepareDecreaseStorage(BusinessActionContext ctx, Long productId, Integer count) {
        Storage storage = storageMapper.selectById(productId);
        if(storage.getResidue()-count < 0){
            throw new RuntimeException("库存不足"+storage.getResidue()+" < "+count);
        }

        //减掉库存，冻结库存增加count
        storageMapper.updateFrozen(productId,storage.getResidue()-count,storage.getFrozen()+count);

        //保存标识
        ResultHolder.setResult(StorageTccAction.class,ctx.getXid(),"p");

        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());

        // 防止重复提交，幂等性
        if(ResultHolder.getResult(StorageTccAction.class,ctx.getXid())==null){
            return true;
        }

        storageMapper.updateFrozenToUsed(productId,count);

        //删除标识
        ResultHolder.removeResult(StorageTccAction.class,ctx.getXid());
        return true;
    }
    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {

        // 防止重复回滚，幂等性
        if(ResultHolder.getResult(StorageTccAction.class,ctx.getXid())==null){
            return true;
        }

        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());

        storageMapper.updateFrozenToResidue(productId,count);

        //删除标识
        ResultHolder.removeResult(StorageTccAction.class,ctx.getXid());
        return true;
    }
}
